package cn.com.blueInfo.HaiYuan.business.purchase.service.impl;

import cn.com.blueInfo.HaiYuan.business.purchase.entity.PurchaseBase;
import cn.com.blueInfo.HaiYuan.business.purchase.entity.PurchaseDetail;
import cn.com.blueInfo.HaiYuan.business.purchase.mapper.PurchaseDetailMapper;
import cn.com.blueInfo.HaiYuan.business.purchase.service.PurchaseDetailService;
import cn.com.blueInfo.HaiYuan.util.ReadExcelInfo;
import cn.com.blueInfo.utils.result.BootstrapTable;
import cn.com.blueInfo.utils.result.ResultInfo;
import cn.com.blueInfo.utils.util.DateUtil;
import cn.com.blueInfo.utils.util.ExcelUtil;
import cn.com.blueInfo.utils.util.JSONUtil;
import cn.com.blueInfo.utils.util.RequestPayload;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 采购单明细行服务接口具体实现
 * @ClassName: PurchaseDetailServiceImpl
 * @author suxch
 * @date 2020年11月7日  下午2:32:53
 */
@Log4j2
@Service
public class PurchaseDetailServiceImpl implements PurchaseDetailService {

    private static final String logTitle = "采购单明细行信息";

    @Autowired
    private PurchaseDetailMapper purchaseDetailMapper;

    /**
     * 分页查询采购单明细行数据具体实现
     * @Title: queryPurchaseDetailDataByPage
     * @param request
     * @return BootstrapTable
     */
    @Override
    public BootstrapTable queryPurchaseDetailDataByPage(HttpServletRequest request) {
        BootstrapTable result = new BootstrapTable();
        JSONObject param = RequestPayload.analysis(request);
        log.info("bootstrapTable请求参数" + param);

        Map<String, Object> paramMap = JSON.parseObject(param.toJSONString());

        try {
            Integer count = purchaseDetailMapper.queryPurchaseDetailInfoCount(paramMap);
            List<PurchaseDetail> purchaseDetailList = purchaseDetailMapper.queryPurchaseDetailInfo(paramMap);
            result.setTotal(count);
            result.setRows(purchaseDetailList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            result.setTotal(0);
            result.setRows(null);
        }
        return result;
    }

    /**
     * 查询采购单明细行数据具体实现
     * @Title: queryPurchaseDetailData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo queryPurchaseDetailData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestParam = request.getParameter("requestParam");
        if (JSONUtil.isToJSONObject(requestParam)) {
            Map<String, Object> paramMap = JSON.parseObject(requestParam);
            Integer limit = Integer.parseInt(paramMap.get("limit").toString());
            try {
                Integer count = purchaseDetailMapper.queryPurchaseDetailInfoCount(paramMap);
                Integer p_len = count / limit;
                if (count % limit > 0) {
                    p_len += 1;
                }
                List<PurchaseBase> printList = new ArrayList<PurchaseBase>();
                for (int p_i = 0; p_i < p_len; p_i++) {
                    paramMap.put("offset", p_i * limit);
                    printList.addAll(purchaseDetailMapper.queryPrintData(paramMap));
                }
                result.setData(printList);
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
                result.setResult(false);
                result.setMessage("打印明细数据获取失败，请联系管理员");
            }
        }
        return result;
    }

    /**
     * 新增采购单明细行数据具体实现
     * @Title: insertPurchaseDetailData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo insertPurchaseDetailData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestData = request.getParameter("requestParam");

        if (JSONUtil.isToJSONObject(requestData)) {
            Date currDate = new Date();
            PurchaseDetail purchaseDetail = JSON.parseObject(requestData, PurchaseDetail.class);
            purchaseDetail.setSystemTime(DateUtil.getFormatDateTime(currDate));
            purchaseDetail.setModifyTime(DateUtil.getFormatDateTime(currDate));

            try {
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("baseId", purchaseDetail.getPurchaseBaseId());
                Integer detailLine = purchaseDetailMapper.queryMaxDetailLineNumber(paramMap);
                if (detailLine == null) {
                    purchaseDetail.setDetailLineNum(1);
                } else {
                    purchaseDetail.setDetailLineNum(detailLine);
                }

                Integer addCount = purchaseDetailMapper.addPurchaseDetailInfo(purchaseDetail);
                if (addCount == 1) {
                    result.setResult(true);
                    result.setMessage(logTitle + "添加成功");
                }
            } catch (Exception e) {
                result.setResult(false);
                result.setError(e.getMessage());
                result.setMessage(logTitle + "增加失败，请联系管理员");
                log.error(e.getMessage());
            }
        } else {
            result.setResult(false);
            result.setMessage("参数异常，请联系管理员");
        }
        return result;
    }

    /**
     * 更新采购单明细行数据具体实现
     * @Title: updatePurchaseDetailData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo updatePurchaseDetailData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestData = request.getParameter("requestParam");

        if (JSONUtil.isToJSONObject(requestData)) {
            Date currDate = new Date();
            PurchaseDetail purchaseDetail = JSON.parseObject(requestData, PurchaseDetail.class);
            purchaseDetail.setModifyTime(DateUtil.getFormatDateTime(currDate));
            try {
                Integer count = purchaseDetailMapper.updatePurchaseDetailInfoByUnid(purchaseDetail);
                if (count == 1) {
                    result.setResult(true);
                    result.setMessage(logTitle + "更新成功");
                }
            } catch (Exception e) {
                result.setResult(false);
                result.setMessage(logTitle + "更新失败，请联系管理员");
                result.setError(e.getMessage());
                log.error(e.getMessage());
            }
        } else {
            result.setResult(false);
            result.setMessage("参数异常");
        }
        return result;
    }

    /**
     * 删除采购单明细行数据具体实现
     * @Title: deletePurchaseDetailData
     * @param request
     * @return ResultInfo
     */
    @Override
    public ResultInfo deletePurchaseDetailData(HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        String requestData = request.getParameter("requestParam");

        if (JSONUtil.isToJSONObject(requestData)) {
            Date currDate = new Date();
            PurchaseDetail purchaseDetail = JSON.parseObject(requestData, PurchaseDetail.class);
            purchaseDetail.setModifyTime(DateUtil.getFormatDateTime(currDate));
            try {
                Integer count = purchaseDetailMapper.updatePurchaseDetailInfoByUnid(purchaseDetail);
                if (count == 1) {
                    result.setResult(true);
                    result.setMessage(logTitle + "删除成功");
                }
            } catch (Exception e) {
                result.setResult(false);
                result.setMessage(logTitle + "删除失败，请联系管理员");
                result.setError(e.getMessage());
                log.error(e.getMessage());
            }
        } else {
            result.setResult(false);
            result.setMessage("参数异常");
        }
        return result;
    }

    /**
     * 下载导入Excel模板文件具体时间
     * @Title: importExcelModel
     * @param request
     * @param response
     */
    @Override
    public void importExcelModel(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> headMap = new LinkedHashMap<String, String>();
        headMap.put("productName", "品名");
        headMap.put("originAddr", "产地");
        headMap.put("drugsType", "种类");
        headMap.put("drugsSpecs", "规格");
        headMap.put("unit", "单位");
        headMap.put("number", "数量");
        headMap.put("unitPrice", "单价");
        headMap.put("money", "金额");
        headMap.put("batchNum", "生产批号");
        headMap.put("productionDate", "生产日期");
        headMap.put("libraryLocation", "库位");
        headMap.put("goodsLocation", "货位");
        headMap.put("quality", "质量情况");

        String title = "随货同行单导入模板";

        ExcelUtil.downloadExcelFile(title, headMap, new JSONArray(), response);
    }

    /**
     * 导入明细行数据具体实现
     * @Title: importDetailData
     * @param request
     * @param file
     * @return ResultInfo
     */
    @Override
    public ResultInfo importDetailData(HttpServletRequest request, MultipartFile file) {
        ResultInfo result = new ResultInfo();
        String fileName = file.getOriginalFilename(); // 获取文件名
        Object resultData = null;
        String requestParam = request.getParameter("requestParam");
        if (JSONUtil.isToJSONObject(requestParam)) {
            JSONObject requestData = JSON.parseObject(requestParam);
            resultData = ReadExcelInfo.importExcelPurchase_Detail(fileName, file);
            if (resultData instanceof String) {
                result.setMessage(resultData.toString());
                result.setResult(false);
                return result;
            }
            JSONArray detailArr = JSON.parseArray(JSON.toJSONString(resultData));
            PurchaseDetail detail = new PurchaseDetail();
            detail.setSystemTime(DateUtil.getFormatDateTime(new Date()));
            detail.setModifyTime(DateUtil.getFormatDateTime(new Date()));
            detail.setStatus("1");
            for (int d_i = 0, d_len = detailArr.size(); d_i < d_len; d_i++) {
                JSONObject oneDetail = detailArr.getJSONObject(d_i);
                oneDetail.putAll(requestData);
                oneDetail.putAll(JSON.parseObject(JSON.toJSONString(detail)));
            }
            List<PurchaseDetail> detailList = JSON.parseArray(JSON.toJSONString(detailArr), PurchaseDetail.class);
            System.out.println(detailList);
            try {
                purchaseDetailMapper.delPurchaseDetailInfoByUnid(requestData.getString("purchaseBaseId"));
                Integer count = purchaseDetailMapper.batchAddPurchaseDetailInfo(detailList);
                if (count > 0) {
                    result.setMessage("数据批量添加成功");
                }
            } catch (Exception e) {
                log.info(e.getMessage());
                result.setResult(false);
                result.setMessage("数据批量添加失败，请联系管理员");
            }
        }
        return result;
    }

}
